package cn.com.xinjinfu.pdoulcProduct.activity.FixedProduct;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.DoWorkActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.ActivitMoneyBean;
import cn.com.xinjinfu.pdoulcProduct.entity.ActivitMoneyBean.ExpGoods.Page;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ActivityManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.TextViewUtil;
import cn.com.xinjinfu.pdoulcProduct.xlistview.XListView;

/**
 * 活动本金
 * Created by android-adt on 2016/1/12.
 */
public class ActivitMoneyAct extends BaseActivity implements XListView.IXListViewListener {
    private int i = 1;
    private XListView mListView;
    private RequestQueue requen;
    private MyAdapter mAdapter;
    private ActivitMoneyBean activitMoneyBean;
    private TextView tv_exper_now, tv_exper_sum, tv_exper_income, tv_actite_info;
    private Button bt_lingqu_more;
    private boolean firstUpData = true;
    private List<Page> page;
    private LinearLayout no_invest_view;
    private Dialog dg;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_mobile_money);

        //初始化头布局
        TitleManager.showTitleWhite(this, "活动本金", "");
        ActivityManager.getInstance().addActivity(this);
        tv_exper_now = (TextView) findViewById(R.id.tv_exper_now);
        tv_exper_sum = (TextView) findViewById(R.id.tv_exper_sum);
        tv_exper_income = (TextView) findViewById(R.id.tv_exper_income);
        tv_actite_info = (TextView) findViewById(R.id.tv_actite_info);
        bt_lingqu_more = (Button) findViewById(R.id.bt_lingqu_more);
        bt_lingqu_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ActivitMoneyAct.this, DoWorkActivity.class));
            }
        });
        tv_actite_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ActivitMoneyAct.this, ActivitMoneyRuleAct.class));
            }
        });
        no_invest_view = (LinearLayout) findViewById(R.id.no_invest_view);
        mListView = (XListView) findViewById(R.id.listView_activite);
        mListView.setPullLoadEnable(true);// 是否显示下拉刷新和上啦加载
        mListView.setPullRefreshEnable(false);
        mAdapter = new MyAdapter(this);
        mListView.setAdapter(mAdapter);
        mListView.setXListViewListener(this);
        requen = Volley.newRequestQueue(this);
        loginRequest("1");
    }

    public void upData() {
        if (activitMoneyBean != null) {
            tv_exper_now.setText(TextViewUtil.getSumLength(activitMoneyBean.getExperNow()));
            tv_exper_sum.setText(TextViewUtil.getSumLength(activitMoneyBean.getExperSum()));
            tv_exper_income.setText(TextViewUtil.getSumLength(activitMoneyBean.getUserHistoryExperIncome()));
            page = activitMoneyBean.getExpGoods().getPage();
            if (page == null || page.isEmpty()) {
                no_invest_view.setVisibility(View.VISIBLE);
            } else {
                mAdapter.setList(page);
                mAdapter.notifyDataSetChanged();
                no_invest_view.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 网络请求
     */
    private void loginRequest(String currPage) {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        if (currPage.equals("1")) {
            dg.show();
        }
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1108");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("currPage", currPage);
            parameters.put("pageSize", "9");
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
            requen.add(request);
        }

    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(ActivitMoneyAct.this, error);
        }
    };
    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            dg.dismiss();
            if (JSONManager.getError(jobj) == -1) {
                activitMoneyBean = JSON.parseObject(jobj.toString(), ActivitMoneyBean.class);
                if (firstUpData) {
                    upData();
                } else {
                    loadData();
                }
            }
        }
    };

    private void loadData() {
        List<Page> newpage = activitMoneyBean.getExpGoods().getPage();
        if (newpage.isEmpty()) {
            ToastManager.showShort(this, "没有更多数据");
        } else {
            page.addAll(newpage);
        }
        mAdapter.setList(page);
        mAdapter.notifyDataSetChanged();
        onLoad();
    }

    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime("刚刚");
    }

    @Override
    public void onRefresh() {
        onLoad();
    }

    @Override
    public void onLoadMore() {
         firstUpData = false;
         loginRequest("" + (++i));
    }

    private class MyAdapter extends BaseAdapter {

        private LayoutInflater mInflater;
        private List<Page> list;

        public void setList(List<Page> list) {
            this.list = list;
        }

        private DateFormat sdf;

        public MyAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);

            sdf = new SimpleDateFormat("yyyy-MM-dd");
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_moblie_money, null);
                holder = new ViewHolder();
                holder.tv_title_money = (TextView) convertView.findViewById(R.id.tv_title_money);
                holder.tv_due_income = (TextView) convertView.findViewById(R.id.tv_due_income);
                holder.tv_stater_time = (TextView) convertView.findViewById(R.id.tv_stater_time);
                holder.tv_stop_time = (TextView) convertView.findViewById(R.id.tv_stop_time);
                holder.tv_cancel = (TextView) convertView.findViewById(R.id.tv_cancel);
                holder.ll_visib_income = (LinearLayout) convertView.findViewById(R.id.ll_visib_income);

                convertView.setTag(holder);//绑定ViewHolder对象

            } else {
                holder = (ViewHolder) convertView.getTag();//取出ViewHolder对象
            }
            Page page = list.get(position);
            if (page != null) {
                if (page.getStatus() == 2) {//黄色 已使用
                    holder.tv_title_money.setTextColor(0xFFF4B942);
                    holder.tv_due_income.setBackgroundColor(0xFFF4B942);
                    holder.tv_cancel.setVisibility(View.GONE);
                    holder.ll_visib_income.setVisibility(View.VISIBLE);
                    holder.tv_due_income.setText("产生收益：" + TextViewUtil.getSumLength(page.getTotal_amount()));
                } else if (page.getStatus() == 1) {//未使用（作废掉）
                    holder.tv_title_money.setTextColor(0xFF666666);
                    holder.tv_due_income.setBackgroundColor(0xFFF77F96);
                    holder.tv_cancel.setVisibility(View.GONE);
                    holder.ll_visib_income.setVisibility(View.VISIBLE);
                } else if (page.getStatus() == -1) {//红色  已结算
                    holder.tv_title_money.setTextColor(0xFF666666);
                    holder.tv_due_income.setBackgroundColor(0xFFF77F96);
                    holder.tv_cancel.setVisibility(View.GONE);
                    holder.ll_visib_income.setVisibility(View.VISIBLE);
                    holder.tv_due_income.setText("到期收益：" + TextViewUtil.getSumLength(page.getTotal_amount()));
                } else if (page.getStatus() == -2) {//灰色  已作废
                    holder.tv_title_money.setTextColor(0xFF999999);
                    holder.tv_cancel.setVisibility(View.VISIBLE);
                    holder.ll_visib_income.setVisibility(View.GONE);
                }
                holder.tv_title_money.setText(TextViewUtil.getSumLength(page.getAmount()));
                holder.tv_stater_time.setText(sdf.format(page.getReceice_time()));
                holder.tv_stop_time.setText("        " + sdf.format(page.getExpire_time()));
            }
            return convertView;
        }
    }

    public final class ViewHolder {
        public TextView tv_title_money;
        public TextView tv_due_income;
        public TextView tv_stater_time;
        public TextView tv_stop_time;
        public TextView tv_cancel;
        public LinearLayout ll_visib_income;
    }


}